package com.lmbsvn.front.controller;

import com.lmbsvn.core.bean.Result;
import com.lmbsvn.core.controller.BaseController;
import com.lmbsvn.core.shiro.bean.UsernamePasswordCaptchaToken;
import com.lmbsvn.core.shiro.helper.ShiroSecurityHelper;
import com.lmbsvn.core.util.ResultUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/")
public class CommonController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    /**
     * 登陆
     * @param Loginname
     * @param Password
     * @param Captcha
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/login.do")
    public @ResponseBody
    Result login(String Loginname, String Password, String Captcha, HttpServletRequest request, HttpServletResponse response) throws Exception{
        //防止同一客户端多次登录
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            log.info("同一客户端防止无意义多次登录......");
            return ResultUtil.success();
        }

        //验证登录
        UsernamePasswordCaptchaToken token = new UsernamePasswordCaptchaToken(Loginname, Password, Captcha);
        token.setRememberMe(false);

        currentUser.login(token);

        //验证登录通过，将用户信息放入session
        if(null != currentUser){
            Session session = currentUser.getSession();
            if(null != session){
                log.info("验证登录通过，将用户信息放入session......");

            }
        }
        return ResultUtil.success();
    }

    /**
     * 退出登陆
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/logout.do")
    public @ResponseBody
    Object logout(HttpServletRequest request, HttpServletResponse response) throws Exception{
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()){
            log.info("退出了。。。。。");
            ShiroSecurityHelper.kickOutUser(subject.getSession());
            subject.logout();
        }
        return ResultUtil.success();
    }
}
